// 1、全局时间筛选器 “前x天”处理
let siFilter; // 时间筛选器定时器
let countFilter = 0; // 计数 超次数据清除si
function adjustTimerFilter() {
  const filterEl = document.querySelector(".m-dashbox-dateTimeFilter");
  if (filterEl) {
    // 1、监听时间筛选器
    document.addEventListener("click", function (event) {
      if (
        event.target.innerText.includes("前7天") ||
        event.target.innerText.includes("前14天") ||
        event.target.innerText.includes("前28天")
      ) {
        let ipt = event.target.querySelector("input");
        if (!ipt) {
          ipt = event.target.parentNode.querySelector("input");
        }
        if (ipt && ipt.checked) ipt.click();
      }
    });
    countFilter++;

    if (siFilter) {
      clearInterval(siFilter);
    }
  }
  if (countFilter > 30 && si) {
    clearInterval(si);
  }
}
siFilter = setInterval(() => {
  adjustTimerFilter();
}, 1000);

// 2、增加快捷时间
let si; // 定时器
let count = 0; // 计数 超次数据清除si
function render() {
  count++;

  // 有快捷时间的门户url
  const portalUrlList = [
    "https://datacenter.3songshu.com/dash/portal/mobile/1_56", // tt测试环境门户url
    // "https://datacenter.3songshu.com/dash/portal/mobile/5_44", // 门户url
  ];
  let renderFlag = false; // 是否需要render
  if(window.top!==window.self) {
    portalUrlList.forEach(item=>{
      if(window.top.location.href.indexOf(item)===0) {
        renderFlag = true
      }
    })
  }
  // 时间筛选器data-id集合
  const dataIdList = [
    "c-jxdovm3hhaTLReeXdoNFDx", // 生产鼠你掌控
    "c-1-754-2251-llhrnonx", // 测试tt
    "c-bZrmUKTgZAUx6xGjz6Ctbq", // 测试tt2
  ];
  let dataId, // 当前data-id
    timeEl,
    hasDataId;
  for (let i = 0; i < dataIdList.length; i++) {
    const item = dataIdList[i];
    timeEl = document.querySelector(`[data-id= ${item}]`);
    if (timeEl) {
      hasDataId = true;
      dataId = item;
      renderFlag = true;
      break;
    }
  }
  if(!renderFlag) return;

  let filterEl = document.querySelector(".m-dashbox-dateTimeFilter");
  if (!timeEl && filterEl) {
    timeEl = filterEl;
    dataId = filterEl.getAttribute("data-id");
  }

  if (timeEl) {
    // 2、增加快捷选择器
    const timeTop = timeEl.offsetTop;

    const quickEl = document.createElement("div");
    quickEl.classList.add("quick--box");
    quickEl.style.position = "absolute";
    quickEl.style.top = `${timeTop - 28}px`;
    quickEl.style.zIndex = "19";
    quickEl.style.fontSize = "14px";
    quickEl.style.fontWeight = "600";
    quickEl.style.padding = "0 10px";
    quickEl.style.display = "flex";
    quickEl.style.height = "28px";
    quickEl.style.color = "#000";

    if (document.querySelector(`[data-id= 'c-1-754-2251-llhrnonx']`)) {
      quickEl.classList.add("quick--box--tt");
      quickEl.style.fontSize = "15px";
    }

    const quickList = ["本月", "昨天", "前7天"];
    quickList.forEach((item) => {
      const childDiv = document.createElement("div");
      childDiv.classList.add("quick--tab");
      childDiv.innerText = item;
      childDiv.style.padding = "5px 12px";
      childDiv.style.cursor = "pointer";
      quickEl.appendChild(childDiv);
    });

    // 监听嵌套Div组件的点击事件
    quickEl.addEventListener("click", (event) => {
      // 获取URL参数
      function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
          return unescape(r[2]);
        }
        return null;
      }

      // 替换指定传入参数的值,paramName为参数,replaceWith为新值
      function replaceParamVal(paramName, replaceWith) {
        var oUrl = this.location.href.toString();
        var re = eval("/(" + paramName + "=)([^&]*)/gi");
        var nUrl = oUrl.replace(re, paramName + "=" + replaceWith);
        return nUrl;
      }

      const dateFormat = function (date, fmt = "yyyy-MM-dd hh:mm:ss") {
        if (!date) {
          return date;
        }
        let o = {
          "M+": date.getMonth() + 1, //月份
          "d+": date.getDate(), //日
          "h+": date.getHours(), //小时
          "m+": date.getMinutes(), //分
          "s+": date.getSeconds(), //秒
          "q+": Math.floor((date.getMonth() + 3) / 3), //季度
          S: date.getMilliseconds(), //毫秒
        };
        if (/(y+)/.test(fmt)) {
          fmt = fmt.replace(
            RegExp.$1,
            (date.getFullYear() + "").substr(4 - RegExp.$1.length)
          );
        }
        for (var k in o) {
          if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(
              RegExp.$1,
              RegExp.$1.length == 1
                ? o[k]
                : ("00" + o[k]).substr(("" + o[k]).length)
            );
          }
        }
        return fmt;
      };
      var today = new Date(new Date().setHours(0, 0, 0, 0));
      let minBound, maxBound;
      if (event.target.innerText.includes("本月")) {
        var firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
        var lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
        minBound = dateFormat(firstDay);
        maxBound = dateFormat(lastDay, "yyyy-MM-dd") + " 24:00:00";
      }
      if (event.target.innerText.includes("昨天")) {
        let lastday = new Date(
          new Date().setHours(0, 0, 0, 0) - 24 * 60 * 60 * 1000
        );
        minBound = dateFormat(lastday);
        maxBound = dateFormat(lastday, "yyyy-MM-dd") + " 24:00:00";
      }
      if (
        event.target.innerText.includes("前7天") ||
        event.target.innerText.includes("前七天")
      ) {
        let lastSevenDay = new Date(
          new Date().setHours(0, 0, 0, 0) - 24 * 60 * 60 * 1000 * 7
        );
        let lastday = new Date(
          new Date().setHours(0, 0, 0, 0) - 24 * 60 * 60 * 1000
        );
        minBound = dateFormat(lastSevenDay);
        maxBound = dateFormat(lastday, "yyyy-MM-dd") + " 24:00:00";
      }
      // 通过集成链接给报告筛选器传递值
      if (minBound && maxBound) {
        let payload = {
          [dataId]: {
            type: "StaticTime",
            minBound: minBound,
            maxBound: maxBound,
          },
        };
        let defaults = getQueryString("defaults");
        let url = location.href;
        let encodeUrl = encodeURIComponent(JSON.stringify(payload));
        if (defaults) {
          url = replaceParamVal("defaults", encodeUrl);
        } else {
          if (url.includes("?")) {
            url += `&defaults=${encodeUrl}`;
          } else {
            url += `?defaults=${encodeUrl}`;
          }
        }
        location.replace(url);
      }
    });
    const timeParentEl = timeEl.parentNode;
    timeParentEl.insertBefore(quickEl, timeEl);
    if (si) {
      clearInterval(si);
    }
  }
  if (count > 30 && si) {
    clearInterval(si);
  }
}

// 定时器调用
si = setInterval(() => {
  render();
}, 1000);
// 即时调用
render();

